﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using FulcrumApi.clients;
using FulcrumApi.helpers;
using HtmlAgilityPack;
using HttpClient;

namespace FulcrumApi.services
{
    public class AuthenticationServices
    {
        private FulcrumHttpClient client;

        public AuthenticationServices(FulcrumHttpClient client)
        {
            this.client = client;
        }

        public string Authenticate(string userName, string password)
        {
            var parameters = new Dictionary<String, String>();
            parameters.Add("utf8", "\u2713");
            parameters.Add("user[email]", userName);
            parameters.Add("user[password]", password);
            parameters.Add("user[remember_me]", "0");
            parameters.Add("commit", "Sign in");
            Stream res = client.doPost("/users/sign_in", parameters);
            String authOk = FulcrumParser.readAsString(res);
            if (!authOk.Contains("<html><body>You are being <a href=\"http://localhost:3000/\">redirected</a>.</body></html>"))
            {
                throw new AuthenticationfailedException();
            }
            return client.authenticityToken;
        }
    }
}
